package com.zhxin.threadLab.singleton.chapter2;

/**
 * @ClassName SingletonObjec
 * @Description //单例模式:延迟加载(懒汉模式) 经典三步骤改进
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/11/30 0030 上午 11:18
 **/
public class SingletonObject {

    volatile private static SingletonObject singletonObject;

    private SingletonObject(){}

    /**
     * 不安全示例1
     * 多线程环境下会出现多个实例对象
     * */
/*     public static SingletonObject getMyInstance(){
        try{
            if(singletonObject ==null){
                Thread.sleep(1000);
                singletonObject = new SingletonObject();
            }
        } catch (InterruptedException e){
            e.printStackTrace();
        }

        return singletonObject;
    }*/

    /**
     * 示例2
     * 加synchronized关键字 效率低
     * */
/*    synchronized public static SingletonObject getMyInstance(){
        try{
            if(singletonObject ==null){
                Thread.sleep(1000);
                singletonObject = new SingletonObject();
            }
        } catch (InterruptedException e){
            e.printStackTrace();
        }

        return singletonObject;
    }*/

    /**
     * 示例3 双检查锁机制 DCL
     *
     * 这是单例模式结合多线程的解决方式
     * */
    public static SingletonObject getMyInstance(){

        try{
            if(singletonObject == null){
                Thread.sleep(1000); // do something
                synchronized (SingletonObject.class){
                    if(singletonObject == null){
                        singletonObject = new SingletonObject();
                    }
                }
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }

        return singletonObject;
    }
}
